<?php

/*
	Class: Pageparts_IndexController

	About: Author
		Rich Joslin

	About: License
		<http://communit.as/docs/license>
*/
class Pageparts_IndexController extends Cts_Controller_Action_Abstract {

	/* Group: Instance Methods */

	function init(){
		parent::init();
	}

	/* Group: Actions */

	/*
		Function: index
	*/
	function indexAction() {
		
		memory_profiler("start Pageparts Index Index Action");
		
		$request = new Cts_Request($this->getRequest());
		$content_table = new PagepartsViewContent();
		$content_table->memCacheOn();
		if ($request->has('rewrite')) {
			if ($request->rewrite) {
				$url_rewrite = str_replace('/'.$this->locale_code, '', $this->getRequest()->getRequestUri());
				if ($this->_identity->isAdmin && $request->has('preview') && $request->preview == 1) {
					$content = $content_table->fetchAll($content_table->select()
						->where("page_url_rewrite = ?", $url_rewrite)
						->where("locale = ?", $this->locale_code)
						->where("publish_on < '".date(DB_DATETIME_FORMAT)."'")
						->order("version desc")
						->group("part_id")
					);
				} else {
					/* OH HAI INLINE SEEKWILLZ */
					$sql = "SELECT p1.* "; 
					$sql .= "FROM `pageparts_vw_content` p1 ";
					$sql .= "INNER JOIN (select part_id,max(version) as version from `pageparts_vw_content` where active=1 group by part_id) as p2 ";
					$sql .= "on p1.part_id = p2.part_id and ";
					$sql .= "(p1.version = p2.version or p2.version is null) ";
					$sql .= "WHERE (page_url_rewrite = '".$url_rewrite."')  ";
					$sql .= "AND (locale = 'en-us') AND (publish_on < '".date(DB_DATETIME_FORMAT)."') ";	
					$memcache = null;
					if(Zend_Registry::isRegistered('memcache')){
						$memcache = Zend_Registry::get("memcache");	
					}
					
					if(!empty($memcache)){
						$alnum = new Zend_Filter_Alnum();
						$cache_signature = "pagepart_".$alnum->filter($url_rewrite);
						Cts_Log::info("Attempting to load cache ".$cache_signature);
						if(!$content = $memcache->load($cache_signature)){
							$content = $content_table->getAdapter()->fetchAll($sql);
							Cts_Log::info("Saving cache ".$cache_signature);
							$memcache->save($content,$cache_signature);
						}
					} else {
						$content = $content_table->getAdapter()->fetchAll($sql);
					}
					
				}
			} else {
				$this->_redirect("/default/auth/missing");
			}
		} elseif (!(boolean)Cts_Registry::get('use_rewrites_only', 'pageparts') && $request->has('id')) {
			// accessing the page directly by ID is only allowed when use_rewrites_only is set to false
			$page_id = $request->id;
			if ($this->_identity->isAdmin && $request->has('preview') && $request->preview == 1) {
				$content = $content_table->fetchAll($content_table->select()
					->where("page_id = ?", $page_id)
					->where("locale = ?", $this->locale_code)
					->where("publish_on < '".date(DB_DATETIME_FORMAT)."'")
					->order("version desc")
					->group("part_id")
				);
			} else {
				$content = $content_table->fetchAll($content_table->select()
					->where("page_id = ?", $page_id)
					->where("locale = ?", $this->locale_code)
					->where("active = 1")
					->where("publish_on < '".date(DB_DATETIME_FORMAT)."'")
					->order("version desc")
					->group("part_id")
				);
			}
		} else {
			$this->_redirect("/default/auth/missing");
		}

		if (is_null($content) || count($content) === 0) {
			$this->_redirect("/default/auth/missing");
		} else {
			if(!is_array($content)){
				$content = $content->toArray();
			}
			$parts = array();
			foreach ($content as $part) {
				$tmp_part = array();
				$tmp_part['template'] = $this->view->theme_path."/modules/pageparts/part_templates/".$part['template_name'].".tpl";
				$tmp_part['metadata'] = unserialize($part['metadata']);
				if(!in_array($part['short_name'],$parts)){
				//if (is_null($parts[$part['short_name']])) {
					$parts[$part['short_name']] = $tmp_part;
				}
			}
			$this->view->parts = $parts;
			// if everything is in working order, all these rows should have the same exact page info
			// so we'll just grab the page variables from the first item in the array
			$this->view->page_template = $this->view->theme_path."/modules/pageparts/page_templates/".$content[0]['page_template_name'].".tpl";
			$this->view->page_title = $content[0]['page_title'];
			
			$this->view->current = "frontend_".$content[0]['page_short_name'];
		}
		
		memory_profiler("end Pageparts Index Index Action");
	}

// 	function navinserttestAction() {
// 
// 		$tree = array(
// 			'frontend_about' => array( // short_name
// 				'parent_short_name' => "main", // used to identify the parent
// 				'link_text' => "About Us",
// 				'url' => "/about.htm",
// 				'sort_order' => 999,
// 				'children' => array( // used to determine parent_ids for child columns
// 					'frontend_philosophy' => array( // short_name
// 						'link_text' => "Our Philosophy",
// 						'url' => "/about/our-philosophy.htm",
// 						'sort_order' => 100,
// 					),
// 					'frontend_cust_svc' => array( // short_name
// 						'link_text' => "Customer Service",
// 						'url' => "/about/customer-service.htm",
// 						'sort_order' => 200,
// 					),
// 				),
// 			),
// 		);
// 
// // TODO - HOLD OFF ON THIS as the ACL roles stuff is all being overhauled
// 
// // dd($tree);
// 
//         // TODO - move this to the place where role is determined, there should only be one place
//         if ($this->_auth->hasIdentity()) {
// 			$nav_role_id = $this->_identity->role_id;
//         } else {
// 			$nav_role_id = Zend_Registry::get('guest_role');
//         }
// 
// 		$nav = new Navigation($nav_role_id);
// 		$nav->insertNavTreeArray($tree);
// 	}

}
